package com.ttc.mBackup.BackupSMS;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.database.Cursor;
import android.text.format.DateFormat;
import android.util.Log;

public class BackupSMS extends SMSFactory {
	private static final String IOEXCEPTION = "IOException";
	private static final String JSONEXCEPTION = "JsonException";
	
	
	private int backupMode;
	private int version;
	private String timeCreate;
	private int threadID;
	
	/**
	 * 
	 * @param _sms
	 * @param phoneContact
	 * @param filename
	 * @param locationCode
	 * @param backupModeCode
	 */
	public BackupSMS(SMSStatistics _sms, ArrayList<String> phone,
			String filename, int locationCode, int backupModeCode) {
		super(_sms, phone, filename, locationCode);
		this.backupMode = backupModeCode;
	}

	/**
	 * 
	 * @param _sms
	 * @param filename
	 * @param locationCode
	 * @param backupModeCode
	 */
	public BackupSMS(SMSStatistics _sms, String filename, int locationCode,
			int backupModeCode) {
		super(_sms, filename, locationCode);
		this.backupMode = backupModeCode;
	}

	/**
	 * 
	 * @return boolean value: true if file create successfully, and false if make exceptions
	 */
	public boolean createBackupFile(){
		threadID = 1;
		JSONArray jsonArray = null;
		//if backup mode is backup incremental with the exist file
		if(backupMode == DialogCode.CODE_PROGRESS_BACKUP_INCREMENTAL){
			String jsonString;
			try {
				//read file and then return content of file as String value
				jsonString = new FileBrowser(filename).ReadBackupFile();
			} catch (IOException e) {
				Log.e(IOEXCEPTION, e.getMessage());
				return false;
			}
			
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(jsonString);
			} catch (JSONException e) {
				Log.e(JSONEXCEPTION, e.getMessage());
				return false;
			}
			
			try {
				//read count of message in the file
				//
				//set sum of message with + 1 because of the for loop in the below
				threadID = jsonObject.getInt("smses") + 1;
			} catch (JSONException e) {
				Log.e(JSONEXCEPTION, e.getMessage());
				return false;
			}
			
			//get content of the messsage in the file
			try {
				jsonArray = jsonObject.getJSONArray("sms");
			} catch (JSONException e) {
				Log.e(JSONEXCEPTION, e.getMessage());
				return false;
			}
			//set version to write in file
			try {
				version = jsonObject.getInt("version") + 1;
			} catch (JSONException e) {
				Log.e(JSONEXCEPTION, e.getMessage());
			}
		//if backup mode is new backup with the new file
		}else if (backupMode == DialogCode.CODE_PROGRESS_BACKUP_NEW){
			version = 1;
			jsonArray = null;
		}
		//set the time to write in the file.
		Date date = new Date();
		String s = DateFormat.format("dd-MM-yy hh:mm:ss", date.getTime()).toString();
		timeCreate = s;
		//make the string that contain all information of the backup file
		String json = CreateJSONString(jsonArray).toString();
		//write backup file
		return (new FileBrowser().makeBackupFile(filename, json));
	}

	/**
	 * 
	 * @param jsonArray
	 * @return
	 */
	private JSONObject CreateJSONString(JSONArray jsonArray) {
		JSONObject jsonObject = new JSONObject();
			try {
				//put all message content to backup file
				jsonObject.put("sms", getMessageArray(jsonArray));
			} catch (JSONException e) {
				Log.e(JSONEXCEPTION, e.getMessage());
				return null;
			}
			//put version information to backup file
			try {
				jsonObject.put("version", version);
			} catch (JSONException e) {
				Log.e(JSONEXCEPTION, e.getMessage());
			}
			
			//put time created information to backup file
			try {
				jsonObject.put("backupTime", timeCreate);
			} catch (JSONException e) {
				Log.e(JSONEXCEPTION, e.getMessage());
			}
			//put sum of message information to backup file
			try {
				jsonObject.put("smses", SMSCount);
			} catch (JSONException e) {
				Log.e(JSONEXCEPTION, e.getMessage());
				return null;
			}
		return jsonObject;
	}
	
	private JSONArray getMessageArray(JSONArray jsonArray1){
		Cursor cursor = null;
		cursor = sms.getCursor();
		JSONArray jsonArray = new JSONArray();
		//similar backup up mode incremental
		if(jsonArray1 != null){
			for (int i = 0; i < jsonArray1.length(); i++) {
				try {
					//put message content to JSONArray
					jsonArray.put(jsonArray1.getJSONObject(i));
				} catch (JSONException e) {
					Log.e(JSONEXCEPTION, e.getMessage());
				}
			}
		}
		
		//if all phone contact is selected
		if(phoneContact.get(0).equals("Check all")){
			while (cursor.moveToNext()) {
				JSONObject jsonObject = new JSONObject();
				jsonObject = putToJSONObject(cursor);
				jsonArray.put(jsonObject);
				threadID++;
			}
			SMSCount = threadID - 1;
		}else if(!phoneContact.get(0).equals("Check all")){
			while (cursor.moveToNext()) {
				for (int i = 1; i < phoneContact.size(); i++) {
					String address = "";
					address = cursor.getString(cursor.getColumnIndex("address"));
					Log.v("check", phoneContact.get(i));
					if(address.equals(phoneContact.get(i))){
						JSONObject jsonObject = new JSONObject();
						jsonObject = putToJSONObject(cursor);
						jsonArray.put(jsonObject);
						threadID++;
					}
				}
			}
			SMSCount = threadID - 1;
		}
		return jsonArray;
	}

	/**
	 * @param cursor
	 * 
	 * @return 
	 */
	public JSONObject putToJSONObject(Cursor cursor) {
		JSONObject jsonObject = new JSONObject();
		
		try {
			jsonObject.put("id", threadID);
		} catch (JSONException e) {
			Log.e(JSONEXCEPTION, e.getMessage());
		}
		
		try {
			jsonObject.put("address", cursor.getString(cursor.getColumnIndex("address")));
		} catch (JSONException e) {
			Log.e(JSONEXCEPTION, e.getMessage());
		}
		
		try {
			jsonObject.put("date", cursor.getLong(cursor.getColumnIndex("date")));
		} catch (JSONException e) {
			Log.e(JSONEXCEPTION, e.getMessage());
		}
		try {
			jsonObject.put("body", cursor.getString(cursor.getColumnIndex("body")));
		} catch (JSONException e) {
			Log.e(JSONEXCEPTION, e.getMessage());
		}
		
		try {
			jsonObject.put("read", cursor.getInt(cursor.getColumnIndex("read")));
		} catch (JSONException e) {
			Log.e(JSONEXCEPTION, e.getMessage());
		}
		
		try {
			jsonObject.put("locked", cursor.getInt(cursor.getColumnIndex("locked")));
		} catch (JSONException e) {
			Log.e(JSONEXCEPTION, e.getMessage());
		}
		
		try {
			jsonObject.put("status", cursor.getInt(cursor.getColumnIndex("status")));
		} catch (JSONException e) {
			Log.e(JSONEXCEPTION, e.getMessage());
		}
		
		try {
			jsonObject.put("type", cursor.getString(cursor.getColumnIndex("type")));
		} catch (JSONException e) {
			Log.e(JSONEXCEPTION, e.getMessage());
		}
		return jsonObject;
	}	
}
